//
//  DevicesTableViewController.m
//  iRMAP
//
//  Created by Ryan Enguero on 3/27/14.
//  Copyright (c) 2014 engueroryan. All rights reserved.
//

#import "DevicesTableViewController.h"

#import "DevicesCell.h"

#import "UiManager.h"

#import "ParserClass.h"

#import "Devices.h"

#import "CateTableCell.h"

#import "SubCateViewController.h"

#import "PostClass.h"

#import "User.h"

#import "Company.h"

#import "DevicesCurrentTemperature-PGS.h"
#import "DevicesCurrentTemperature-Platinum.h"
#import "DevicesCurrentTemperature-CO2Incubator.h"
#import "DevicesCurrentTemperature-EGS-G2.h"
#import "DevicesCurrentTemperature-OFA_IFA_IFC_INA.h"
#import "SetPointViewController.h"
#import "MeasurementViewController.h"
#import "loadingView.h"
#import "MeasurementTableViewController.h"

#import "IIViewDeckController.h"


#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface DevicesTableViewController () <UIFolderTableViewDelegate> {

    NSString *sessionIDStr;
    NSString *domainIDStr;
}

@property (strong, nonatomic) SubCateViewController *subVc;
@property (strong, nonatomic) NSDictionary *currentCate;


@end

int arrowAnimationState = 0;
@implementation DevicesTableViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Devices", @"Devices");
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(0.0f, 0.0f, 18.0f, 17.0f)];
        [btn addTarget:self action:@selector(buttonEN:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"Menu_button.png"] forState:UIControlStateNormal];
        UIBarButtonItem *eng_btn = [[UIBarButtonItem alloc] initWithCustomView:btn];
        
        self.navigationItem.leftBarButtonItem = eng_btn;
        
        
        
        
    }

    return self;
}








-(void)buttonEN:(id)sender
{
    NSLog(@"English language");
    
    [[UiManager sharedItems] openLeft];
}


-(NSArray *)cates
{
    if (_cates == nil){
        
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"Category" withExtension:@"plist"];
        _cates = [NSArray arrayWithContentsOfURL:url];
        
    }
    
    return _cates;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
//    UIView *mainView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//    
//    [mainView setBackgroundColor:[UIColor blueColor]];
//    
//    [mainView addSubview:self.view];
    
    
    //MainMenu_Bg
   // self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tmall_bg_furley.png"]];
    UIImage *image = [UIImage imageNamed:@"MainMenu_Bg"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    UITableView *tableView = (UITableView*)self.view;
    tableView.backgroundView = imageView;
    //[tableView setScrollEnabled:NO];
    
    [self.view setBackgroundColor:[UIColor clearColor]];

    //self.navigationController.navigationBar.translucent = NO;
    //self.view.backgroundColor = [UIColor redColor];
    //self.navigationItem.title = @"AAAA";
    
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Esco_Banner_new"] forBarMetrics:UIBarMetricsDefault];
    
    [UiManager navigationHeaderWithTitle:@"Devices" andViewController:self];
    
    
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tabBarController.tabBar setHidden:NO];
    [self.navigationController.navigationBar setHidden:NO];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] deviceDetails] count];

    //self.cates.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
    loadingView * loading = [xib objectAtIndex:0];
    [self.view addSubview:loading];
    
    [loading.imgLoading setAlpha:0.0];
    [loading.imgLoading2 setAlpha:1.0];
    
    [loading.imgBg setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:loading];
    
    
    
    
    
//    static NSString *CellIdentifier = @"cate_cell";
//    
//    CateTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    
//    if (cell == nil) {
//        cell = [[CateTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle
//                                     reuseIdentifier:CellIdentifier];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        
//    }
//    
//    NSDictionary *cate = [self.cates objectAtIndex:indexPath.row];
//    cell.logo.image = [UIImage imageNamed:[[cate objectForKey:@"imageName"] stringByAppendingString:@".png"]];
//    cell.title.text = [cate objectForKey:@"name"];
//    
//    NSMutableArray *subTitles = [[NSMutableArray alloc] init];
//    NSArray *subClass = [cate objectForKey:@"subClass"];
//    for (int i=0; i < MIN(4,  subClass.count); i++) {
//        [subTitles addObject:[[subClass objectAtIndex:i] objectForKey:@"name"]];
//    }
//    cell.subTtile.text = [subTitles componentsJoinedByString:@"/"];
//   // [subTitles release];
//    
//    return cell;
    
    static NSString *CellIdentifier = @"Cell";
    
    DevicesCell *cell = (DevicesCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    self.delegate = cell;

    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DevicesCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    // Configure the cell...
    
    
    
    dispatch_async(kBgQueue, ^{
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [loading removeFromSuperview];
            
            UIImage *image = [UIImage imageNamed:@"MainMenu_Bg_blur"];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            UITableView *tableView = (UITableView*)self.view;
            tableView.backgroundView = imageView;
            
            Devices *devices = [[ParserClass sharedItems] deviceDetails][indexPath.row];
            
            cell.nameCaption.text = [NSString stringWithFormat:@"%@ (%@)", [devices deviceName], [devices deviceType]];
            [cell.icon addTarget:self action:@selector(statusAcknowledge:) forControlEvents:UIControlEventTouchUpInside];
            
            if ([[devices deviceType] isEqualToString:@"ultf_gold"] || [[devices deviceType] isEqualToString:@"ultf_silver"] ) {
                
                DevicesCurrentTemperature_PGS *devicesGoldSilver = [[ParserClass sharedItems] deviceDetails][indexPath.row];
                
                if ([[devicesGoldSilver chamberTemperatureSensor] isEqualToString:@"<null>"]) {
                    cell.tempCaption.text = @"0°C";
                }else{
                cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesGoldSilver chamberTemperatureSensor]];
                }
                
                
                if ([[devicesGoldSilver connectionState] isEqualToString:@"0"]) {
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Error.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesGoldSilver connectionState] isEqualToString:@"1"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Check.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesGoldSilver connectionState] isEqualToString:@"2"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Warning.png"] forState:UIControlStateNormal];
                    
                }
                
            }else if ([[devices deviceType] isEqualToString:@"ultf_platinum"]){
                
                DevicesCurrentTemperature_Platinum *devicesPlatinum = [[ParserClass sharedItems] deviceDetails][indexPath.row];
                
                if ([[devicesPlatinum chamberTemperatureSensor] isEqualToString:@"<null>"]) {
                    cell.tempCaption.text = @"0°C";
                }else{
                cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesPlatinum chamberTemperatureSensor]];
                }
                
                if ([[devicesPlatinum connectionState] isEqualToString:@"0"]) {
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Error.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesPlatinum connectionState] isEqualToString:@"1"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Check.png"] forState:UIControlStateNormal];
                }else if ([[devicesPlatinum connectionState] isEqualToString:@"2"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Warning.png"] forState:UIControlStateNormal];
                }
                
            }else if ([[devices deviceType] isEqualToString:@"co2_incubator"]){
                
                DevicesCurrentTemperature_CO2Incubator *devicesIncubator = [[ParserClass sharedItems] deviceDetails][indexPath.row];
                
                if ([[devicesIncubator temperatureSensor] isEqualToString:@"<null>"]) {
                    cell.tempCaption.text = @"0°C";
                }else{
                    cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesIncubator temperatureSensor]];
                }
                
               // cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesIncubator temperatureSensor]];
                
                if ([[devicesIncubator connectionState] isEqualToString:@"0"]) {
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Error.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesIncubator connectionState] isEqualToString:@"1"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Check.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesIncubator connectionState] isEqualToString:@"2"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Warning.png"] forState:UIControlStateNormal];
                }
                
            }else if ([[devices deviceType] isEqualToString:@"ecs-g2"]){
                
                DevicesCurrentTemperature_EGS_G2 *devicesEGSG2 = [[ParserClass sharedItems] deviceDetails][indexPath.row];
                //cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesEGSG2 inflowsensor]];
                
                if ([[devicesEGSG2 inflowsensor] isEqualToString:@"<null>"]) {
                    cell.tempCaption.text = @"0°C";
                }else{
                    cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesEGSG2 inflowsensor]];
                }
                
                if ([[devicesEGSG2 connectionState] isEqualToString:@"0"]) {
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Error.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesEGSG2 connectionState] isEqualToString:@"1"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Check.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesEGSG2 connectionState] isEqualToString:@"2"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Warning.png"] forState:UIControlStateNormal];
                }
                
            }else if ([[devices deviceType] isEqualToString:@"ofa"] || [[devices deviceType] isEqualToString:@"ifa"] || [[devices deviceType] isEqualToString:@"ifc"] || [[devices deviceType] isEqualToString:@"ina"]){
                
                DevicesCurrentTemperature_OFA_IFA_IFC_INA *devicesOFAIFAIFCINA = [[ParserClass sharedItems] deviceDetails][indexPath.row];
                
                if ([[devicesOFAIFAIFCINA chamberTemperatureSensor] isEqualToString:@"<null>"]) {
                    cell.tempCaption.text = @"0°C";
                }else{
                    cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesOFAIFAIFCINA chamberTemperatureSensor]];
                }
                
                //cell.tempCaption.text = [NSString stringWithFormat:@"%@°C",[devicesOFAIFAIFCINA chamberTemperatureSensor]];
                
                if ([[devicesOFAIFAIFCINA connectionState] isEqualToString:@"0"]) {
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Error.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesOFAIFAIFCINA connectionState] isEqualToString:@"1"]){
                    
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Check.png"] forState:UIControlStateNormal];
                    
                }else if ([[devicesOFAIFAIFCINA connectionState] isEqualToString:@"2"]){
                    
                    [cell.icon setImage:[UIImage imageNamed:@"Status_Warning.png"] forState:UIControlStateNormal];
                }
                
            }
            
            cell.timeStampCaption.text = [NSString stringWithFormat:@"%@",[NSDate date]];
            cell.icon.tag = indexPath.row;
            
            
            
        });
    });
  

    return cell;

}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    DevicesCell *cell = (DevicesCell*) [tableView cellForRowAtIndexPath:indexPath];
    
    arrowAnimationState = 1;
    
    if (arrowAnimationState == 1) {
        [cell.img_arrow setImage:[UIImage imageNamed:@"TableArrow_Up.png"]];
        arrowAnimationState = 2;
    }else if (arrowAnimationState == 2){
        
        arrowAnimationState = 1;
    }
    
    
    self.pathIndex = indexPath;
    
    SubCateViewController *subVc = [[SubCateViewController alloc]
                                     initWithNibName:NSStringFromClass([SubCateViewController class])
                                     bundle:nil];
    NSDictionary *cate = [self.cates objectAtIndex:indexPath.row];
    subVc.subCates = [cate objectForKey:@"subClass"];
    self.currentCate = cate;
    subVc.cateVC = self;
    
    self.tableView.scrollEnabled = NO;
    UIFolderTableView *folderTableView = (UIFolderTableView *)tableView;
    [folderTableView openFolderAtIndexPath:indexPath WithContentView:subVc.view
                                 openBlock:^(UIView *subClassView, CFTimeInterval duration, CAMediaTimingFunction *timingFunction){
                                     // opening actions
                                      self.tableView.scrollEnabled = NO;
                                     
                                     
                                 }
                                closeBlock:^(UIView *subClassView, CFTimeInterval duration, CAMediaTimingFunction *timingFunction){
                                    // closing actions
                                    
                                }
                           completionBlock:^{
                               // completed actions
                               self.tableView.scrollEnabled = YES;
                               [cell.img_arrow setImage:[UIImage imageNamed:@"TableArrow_Down.png"]];
                               arrowAnimationState = 1;
                           }];
    
    
    
}

-(CGFloat)tableView:(UIFolderTableView *)tableView xForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(void)subCateBtnAction:(UIButton *)btn
{
    
//    NSDictionary *subCate = [[self.currentCate objectForKey:@"subClass"] objectAtIndex:btn.tag];
//    NSString *name = [subCate objectForKey:@"name"];
//    UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:@"AAAA"
//                                                         message:[NSString stringWithFormat:@"BB:%@, ID: %@", name, [subCate objectForKey:@"classID"]]
//                                                        delegate:nil
//                                               cancelButtonTitle:@"APO"
//                                               otherButtonTitles:nil];
//    [Notpermitted show];
   // [Notpermitted release];
    
    NSLog(@"tag = %i", btn.tag);
}

- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation
{
    
    //    if(orientationToLandscape)
    //    {
    //        //when we manually changed, show in Portrait
    //        return UIInterfaceOrientationLandscapeRight;
    //    }
    //    else
    //    {
    //before manual orientation change, we allow any orientation
    return UIInterfaceOrientationLandscapeRight;
    //  }
}

- (void)graph{
    
    NSLog(@"Graph = %i", self.pathIndex.row);
    
  
    orientationToLandscape = YES;
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
    loadingView * loading = [xib objectAtIndex:0];
    
    [loading setFrame:CGRectMake(0, -200, 93, 47)];
    
    
    //[loading setBackgroundColor:[UIColor redColor]];
    
    
    [loading.imgLoading2 setAlpha:1.0];
    [loading.imgLoading setAlpha:0.0];
    
    UIView* bgLoading = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    
    
    [bgLoading addSubview:loading];
    
    [self.view addSubview:bgLoading];
        
    Devices *devices = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
    User *user = [[ParserClass sharedItems] userdetails][0];
    ParserClass *parser = [ParserClass sharedItems];
    
    
    [parser getEquipmentType:[devices deviceType]];
    
    
    dispatch_async(kBgQueue, ^{
        
        
        NSDictionary *json = [[PostClass sharedItems] getSensorLog:[user sessionID] andDomainID:[[ParserClass sharedItems] domainID] andDeviceID:[devices freezerId]];
        
        
        if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [parser sensorLogs:json];
                
                [parser getEquipmentType:[devices deviceType]];
                
                [bgLoading removeFromSuperview];
                
               // [self.navigationController pushViewController:[[UiManager sharedItems] graphViewController] animated:YES];
                
              //  [self.delegate dismissGraph];
                
                [self presentViewController:[[UiManager sharedItems] graphViewController] animated:YES completion:nil];
            
            });
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [bgLoading removeFromSuperview];
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"code"]] message:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"message"]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                
                [alertView show];
            });
            
            
        }
    });

    
    
    
}



- (void)setPoint{

    NSLog(@"Set Point = %i", self.pathIndex.row);
    
    Devices *devices = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
    
    
    
    if ([[devices deviceType] isEqualToString:@"ultf_gold"] || [[devices deviceType] isEqualToString:@"ultf_silver"] ) {
        
        DevicesCurrentTemperature_PGS *devicesGoldSilver = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
        
//        self.delegate = [UiManager sharedItems].setpointView;
//        [self.delegate getSetPoint:[devicesGoldSilver chamberSetPoint]];
        
        if ([[devicesGoldSilver chamberTemperatureSensor] isEqualToString:@"<null>"]) {
            //cell.tempCaption.text = @"0°C";
            
            [[ParserClass sharedItems] getSetPoint:@"0"];

        }else{
        
        [[ParserClass sharedItems] getSetPoint:[devicesGoldSilver chamberSetPoint]];
        }
      
        
    }else if ([[devices deviceType] isEqualToString:@"ultf_platinum"]){
        
        DevicesCurrentTemperature_Platinum *devicesPlatinum = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
        
//        self.delegate = [UiManager sharedItems].setpointView;
//        [self.delegate getSetPoint:[devicesPlatinum chamberSetPoint]];

        
        if ([[devicesPlatinum chamberTemperatureSensor] isEqualToString:@"<null>"]) {
            //cell.tempCaption.text = @"0°C";
            
            [[ParserClass sharedItems] getSetPoint:@"0"];
            
        }else{
            
            [[ParserClass sharedItems] getSetPoint:[devicesPlatinum chamberSetPoint]];
        }
        
      //  [[ParserClass sharedItems] getSetPoint:[devicesPlatinum chamberSetPoint]];
        
        
    }else if ([[devices deviceType] isEqualToString:@"co2_incubator"]){
        
        DevicesCurrentTemperature_CO2Incubator *devicesIncubator = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
        
//        self.delegate = [UiManager sharedItems].setpointView;
//        [self.delegate getSetPoint:[devicesIncubator temperatureSetPoint]];
        
        
        if ([[devicesIncubator temperatureSetPoint] isEqualToString:@"<null>"]) {
            //cell.tempCaption.text = @"0°C";
            
            [[ParserClass sharedItems] getSetPoint:@"0"];
            
        }else{
            
            [[ParserClass sharedItems] getSetPoint:[devicesIncubator temperatureSetPoint]];
        }
        
//        [[ParserClass sharedItems] getSetPoint:[devicesIncubator temperatureSetPoint]];

        
    }else if ([[devices deviceType] isEqualToString:@"ecs-g2"]){
        
        DevicesCurrentTemperature_EGS_G2 *devicesEGSG2 = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
        
//        self.delegate = [UiManager sharedItems].setpointView;
//        [self.delegate getSetPoint:[devicesEGSG2 temperatureSensor]];
        if ([[devicesEGSG2 temperatureSensor] isEqualToString:@"<null>"]) {
            //cell.tempCaption.text = @"0°C";
            
            [[ParserClass sharedItems] getSetPoint:@"0"];
            
        }else{
            
            [[ParserClass sharedItems] getSetPoint:[devicesEGSG2 temperatureSensor]];
        }
        
        //[[ParserClass sharedItems] getSetPoint:[devicesEGSG2 temperatureSensor]];

        
    }else if ([[devices deviceType] isEqualToString:@"ofa"] || [[devices deviceType] isEqualToString:@"ifa"] || [[devices deviceType] isEqualToString:@"ifc"] || [[devices deviceType] isEqualToString:@"ina"]){
        
        DevicesCurrentTemperature_OFA_IFA_IFC_INA *devicesOFAIFAIFCINA = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
        
//        self.delegate = [UiManager sharedItems].setpointView;
//        [self.delegate getSetPoint:[devicesOFAIFAIFCINA chamberSetPoint]];

        
        if ([[devicesOFAIFAIFCINA chamberSetPoint] isEqualToString:@"<null>"]) {
            //cell.tempCaption.text = @"0°C";
            
            [[ParserClass sharedItems] getSetPoint:@"0"];
            
        }else{
            
            [[ParserClass sharedItems] getSetPoint:[devicesOFAIFAIFCINA chamberSetPoint]];
        }
        
      //  [[ParserClass sharedItems] getSetPoint:[devicesOFAIFAIFCINA chamberSetPoint]];
    }

    [self.navigationController pushViewController:
     [[UiManager sharedItems] setpointViewController] animated:YES];
}

- (void)measurement{
    
    
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
    loadingView * loading = [xib objectAtIndex:0];
    
    [loading setFrame:CGRectMake(0, -200, 93, 47)];
    
    
    //[loading setBackgroundColor:[UIColor redColor]];
    
    
    [loading.imgLoading2 setAlpha:1.0];
    [loading.imgLoading setAlpha:0.0];
    
    UIView* bgLoading = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    
    
    [bgLoading addSubview:loading];
    
    [self.view addSubview:bgLoading];
    
    
    NSLog(@"measurement = %i", self.pathIndex.row);
    
    Devices *devices = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
    User *user = [[ParserClass sharedItems] userdetails][0];
    ParserClass *parser = [ParserClass sharedItems];
    
    [parser getFreezerID:[devices freezerId]];
    [parser getEquipmentType:[devices deviceType]];

    
    dispatch_async(kBgQueue, ^{
        
        
        NSDictionary *json = [[PostClass sharedItems] getSensorLog:[user sessionID] andDomainID:[[ParserClass sharedItems] domainID] andDeviceID:[devices freezerId]];
        
        
        if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [parser sensorLogs:json];
            
            [parser getEquipmentType:[devices deviceType]];
            
            [bgLoading removeFromSuperview];
            
            [self.navigationController pushViewController: [[UiManager sharedItems] measurementViewController] animated:YES];
        });
            
        }else{
        
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [bgLoading removeFromSuperview];
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"code"]] message:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"message"]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                
                [alertView show];
            });

        
        }
    });
    
    
    
//    self.delegate = [UiManager sharedItems].measurementView;
//    [self.delegate setMeasurementsData:[devices deviceType]];
    
    
    
    
  
    
    
}

- (void)logs{
    
    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
    loadingView * loading = [xib objectAtIndex:0];
    
    [loading setFrame:CGRectMake(0, -200, 93, 47)];
    
    //[loading setBackgroundColor:[UIColor redColor]];
    
    
    [loading.imgLoading2 setAlpha:1.0];
    [loading.imgLoading setAlpha:0.0];
    
    UIView* bgLoading = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    
    
    [bgLoading addSubview:loading];

    
    [self.view addSubview:bgLoading];
    
    NSLog(@"Logs = %i", self.pathIndex.row);
    
    Devices *devices = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
    User *user = [[ParserClass sharedItems] userdetails][0];
    
    ParserClass *parser = [ParserClass sharedItems];
    
    
    dispatch_async(kBgQueue, ^{
        
        
        NSDictionary *json = [[PostClass sharedItems] getAlarmLog:[user sessionID] andDomainID:[parser domainID] andDeviceID:[devices freezerId]];
        
        NSDictionary *jsonEvent = [[PostClass sharedItems] getEventLog:[user sessionID] andDomainID:[parser domainID] andDeviceID:[devices freezerId]];
        
        
        if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [parser alarmLogs:json];
                
                [parser eventLogs:jsonEvent];
                
            [bgLoading removeFromSuperview];
                
            [self.navigationController pushViewController:[[UiManager sharedItems]logsViewController] animated:YES];

            });
            
        }else{
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [bgLoading removeFromSuperview];

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"code"]] message:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"message"]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                
                [alertView show];
            });
            
            
        }
    });

    
    
    
    

    
    
}

- (IBAction)statusAcknowledge:(id)sender{
    
    
    
    Devices *devices = [[ParserClass sharedItems] deviceDetails][[sender tag]];
    
    User *user = [[ParserClass sharedItems] userdetails][0];
    
    ParserClass *parser = [ParserClass sharedItems];
    
    NSDictionary *status = [[PostClass sharedItems] statusAcknowledgeWithSessionID:[user sessionID] andDomainID:[parser domainID] andDeviceID:[devices freezerId]];
    
    if ([[[status objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Status Acknowledged" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        
        [alertView show];
    }else{
    
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Status Not Acknowledged" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        
        [alertView show];
    }
    
    
    
//    if ([[devices deviceType] isEqualToString:@"ultf_gold"] || [[devices deviceType] isEqualToString:@"ultf_silver"] ) {
//        
//        DevicesCurrentTemperature_PGS *devicesGoldSilver = [[ParserClass sharedItems] deviceDetails][[sender tag]];
//        
//        
//        [[PostClass sharedItems] statusAcknowledgeWithSessionID:[user sessionID] andDomainID:[parser domainID] andDeviceID:[devicesGoldSilver freezerId]];
//        
//        
//    }else if ([[devices deviceType] isEqualToString:@"ultf_platinum"]){
//        
//        DevicesCurrentTemperature_Platinum *devicesPlatinum = [[ParserClass sharedItems] deviceDetails][[sender tag]];
//        
//    }else if ([[devices deviceType] isEqualToString:@"co2_incubator"]){
//        
//        DevicesCurrentTemperature_CO2Incubator *devicesIncubator = [[ParserClass sharedItems] deviceDetails][[sender tag]];
//        
//    }else if ([[devices deviceType] isEqualToString:@"ecs-g2"]){
//        
//        DevicesCurrentTemperature_EGS_G2 *devicesEGSG2 = [[ParserClass sharedItems] deviceDetails][[sender tag]];
//        
//        
//    }else if ([[devices deviceType] isEqualToString:@"ofa"] || [[devices deviceType] isEqualToString:@"ifa"] || [[devices deviceType] isEqualToString:@"ifc"] || [[devices deviceType] isEqualToString:@"ina"]){
//        
//        DevicesCurrentTemperature_OFA_IFA_IFC_INA *devicesOFAIFAIFCINA = [[ParserClass sharedItems] deviceDetails][[sender tag]];
//        
//    }

}

#pragma mark - MainPageViewController Delegate

- (void)getSessionID:(NSString *)seesionID andDomainID:(NSString *)domainID andDeviceID:(NSString *)deviceID{

    sessionIDStr = seesionID;
    domainIDStr = domainID;
}

//- (void)viewDidLoad
//{
//    [super viewDidLoad];
//    
//        // Uncomment the following line to preserve selection between presentations.
//    // self.clearsSelectionOnViewWillAppear = NO;
//    
//    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    
//    NSLog(@"count devices = %i",[[[ParserClass sharedItems] deviceDetails] count]);
//
//}
//
//- (void)didReceiveMemoryWarning
//{
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}
//
//#pragma mark - Table view data source
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
////#warning Potentially incomplete method implementation.
//    // Return the number of sections.
//    return 1;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
////#warning Incomplete method implementation.
//    // Return the number of rows in the section.
//    return [[[ParserClass sharedItems] deviceDetails] count];
//    
//}
//
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
////    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
////    
////    // Configure the cell...
////    
////    return cell;
//    
//    static NSString *CellIdentifier = @"Cell";
//    
//    DevicesCell *cell = (DevicesCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    
//    if (cell == nil) {
//        
//        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DevicesCell" owner:self options:nil];
//        cell = [nib objectAtIndex:0];
//    }
//    
//    // Configure the cell...
//    
//    Devices *devices = [[ParserClass sharedItems] deviceDetails][indexPath.row];
//    
//    cell.nameCaption.text = [devices deviceName];
//  //  cell.tempCaption.text =
//    cell.timeStampCaption.text = [NSString stringWithFormat:@"%@",[NSDate date]];
//    
//    
//    return cell;
//
//}
//
//
///*
//// Override to support conditional editing of the table view.
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    // Return NO if you do not want the specified item to be editable.
//    return YES;
//}
//*/
//
///*
//// Override to support editing the table view.
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        // Delete the row from the data source
//        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
//        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
//    }   
//}
//*/
//
///*
//// Override to support rearranging the table view.
//- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
//{
//}
//*/
//
///*
//// Override to support conditional rearranging of the table view.
//- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    // Return NO if you do not want the item to be re-orderable.
//    return YES;
//}
//*/
//
//
//#pragma mark - Table view delegate
//
//// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    // Navigation logic may go here, for example:
//    // Create the next view controller.
//   
//    // Pass the selected object to the new view controller.
//    
//   // Devices *devices = [[ParserClass sharedItems] deviceDetails][indexPath.row];
//    
//    // Push the view controller.
//    [self.navigationController pushViewController:[[UiManager sharedItems] deviceInfo] animated:YES];
//}


@end
